package com.study.filter;

import com.study.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 授权过滤器
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    public TokenAuthenticationFilter(AuthenticationManager authenticationManager,TokenManager tokenManager,RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.tokenManager=tokenManager;
        this.redisTemplate=redisTemplate;
    }



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
       //获取当前认证成功用户权限信息
       UsernamePasswordAuthenticationToken authRequest= getAuthentication(request);
       //有权限信息，放到权限上下文中
        if (authRequest!=null){
            /**
             * securitycontextholder.getcontext().setauthentication()认证信息存储节点
             */
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从hedaer中获取token
        String token = request.getHeader("token");
        if (token!=null){
            //从token中获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
            //从redis中获取对呀权限列表信息
            List<String> permissionValue =( List<String>) redisTemplate.opsForValue().get(username);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for (String permission:permissionValue
                 ) {
                SimpleGrantedAuthority auth=new SimpleGrantedAuthority(permission);
            }
            return new UsernamePasswordAuthenticationToken(username,token,authorities);
        }
       return null;
    }


}
